package m.jclecai.com.ui;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.LottoTrendActivity;
import m.jclecai.com.activity.WebHelperActivity;
import m.jclecai.com.adapter.BallsAdapter;
import m.jclecai.com.adapter.independentLotteryAdapter.PLS_SD_QXCA_LotteryAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.BallItem;
import m.jclecai.com.bean.IssueInfoBean;
import m.jclecai.com.bean.MissDataBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.inter.IAdapterChange;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.MakeRandomUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ShakeUtils;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.BallGridView;
import m.jclecai.com.view.common.BottomBar;
import m.jclecai.com.view.common.VeticalDrawerLayout;
import q.rorbin.badgeview.Badge;

/**
 * Created by hp on 2017/3/21.
 * 选号界面 ssq dlt qlc
 */

public class BetSSQ_DLT_QLCActivity extends BaseActivity implements
        View.OnClickListener, IAdapterChange,
        AdapterView.OnItemClickListener, View.OnTouchListener {

    private BallsAdapter redBallsAdapter, blueBallsAdapter;
    private PopupWindow pop;
    private TextView tv_number_money;
    private TextView tv_term;
    private TextView tv_date;
    private TextView tv_count;
    //选择的红球 蓝球的总数
    private int redBallCount, blueBallCount;
    //投注的号码
    private List<String> redCode = new LinkedList<>();
    private List<String> blueCode = new LinkedList<>();
    //彩种红蓝球数量
    private int redCount, blueCount;
    //彩种金额计算比率
    private int redMultiple, blueMultiple;
    private TextView tv_hint;
    private String type;
    private ImageView iv_add_selector;

    private ArrayList<String> ballNumber = new ArrayList<>();
    //玩法及模式
    private ArrayList<String> mode = new ArrayList<>();
    //注数及金额
    private ArrayList<String> numMoney = new ArrayList<>();
    //总金额
    private int totalMoney;
    //总注数
    private int totalNum;
    private ListView lv_history;
    //   private SSQ_DLT_QLC_LotteryAdapter independentLotteryAdapter;
    private PLS_SD_QXCA_LotteryAdapter independentLotteryAdapter;
    private int topHeight;

    private MissDataBean.Omission omission;
    private ImageView iv_unfold;
    private LinearLayout ll;

    public String TAG = "BetSSQ_DLT_QLCActivity";
    private TextView mTvMissData;
    private VeticalDrawerLayout mVdlLayout;

    //listView
    BallGridView gridview_ssq_red_ball;
    BallGridView gridview_ssq_blue_ball;
    private BottomBar mBottomBar;
    private View mLlTitle;
    private ShakeUtils mShakeUtils;
    //   private View ll_bottom;


    @Override
    protected int getContentView() {
        return R.layout.betting_activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mShakeUtils.register();
    }

    @Override
    protected void initView() {
        leftOptionText("");
        rightOptionText("", R.drawable.action_menu);
        Intent intent = getIntent();
        type = intent.getStringExtra("type");

        tv_term = (TextView) findViewById(R.id.tv_term);
        tv_date = (TextView) findViewById(R.id.tv_date);

        ImageView iv_shake = (ImageView) findViewById(R.id.iv_shake);
        iv_shake.setOnClickListener(this);

        tv_number_money = (TextView) findViewById(R.id.tv_number_money);

        //选号部分
        gridview_ssq_red_ball = (BallGridView) findViewById(R.id.gridview_ssq_red_ball);
        gridview_ssq_red_ball.setOnItemClickListener(this);
        gridview_ssq_blue_ball = (BallGridView) findViewById(R.id.gridview_ssq_blue_ball);
        gridview_ssq_blue_ball.setOnItemClickListener(this);

        redBallsAdapter = new BallsAdapter(this);
        blueBallsAdapter = new BallsAdapter(this);

        gridview_ssq_red_ball.setAdapter(redBallsAdapter);
        gridview_ssq_blue_ball.setAdapter(blueBallsAdapter);

        //垂直的抽屉；
        mVdlLayout = ((VeticalDrawerLayout) findViewById(R.id.vdl_layout));
        mVdlLayout.setOnDragStatusChange(new VeticalDrawerLayout.OnDragStatusChange() {
            @Override
            public void onOpen() {

            }

            @Override
            public void onClose() {

            }

            @Override
            public void OnDrag(float percent) {
                //这里我们执行动画；
                if (percent >= 0 && percent <= 1) {
                    Float evaluate = BaseUtils.evaluate(percent, 0, 180);
                    iv_unfold.setRotation(evaluate);
                }
            }
        });


        //底部状态栏
        RelativeLayout rl_add = (RelativeLayout) findViewById(R.id.rl_add);
        rl_add.setOnTouchListener(this);
        iv_add_selector = (ImageView) findViewById(R.id.iv_add_selector);

        tv_count = (TextView) findViewById(R.id.tv_count);//注数
        tv_hint = (TextView) findViewById(R.id.tv_hint);

        mLlTitle = findViewById(R.id.ll_title);

        Button bt_bottom_left = (Button) findViewById(R.id.bt_bottom_left);
        bt_bottom_left.setOnClickListener(this);
        Button bt_bottom_right = (Button) findViewById(R.id.bt_bottom_right);
        bt_bottom_right.setOnTouchListener(this);

        //底部的title所在的区域；
        // ll_bottom = findViewById(R.id.ll_bottom);

        mBottomBar = ((BottomBar) findViewById(R.id.bb_bottom_bar));
        mBottomBar.setLeftButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里实现机选和清空的操作；
                TextView textView = (TextView) v;
                String text = textView.getText().toString();
                if ("机选".equals(text)) {
                    //随机选中一个
                    randomSelect();
                    textView.setText("清空");
                } else {
                    //清空逻辑；
                    clearBall();
                    textView.setText("机选");
                }
            }
        });
        mBottomBar.setRightButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里我们将执行下一步的操作
                if (ballNumber.size() > 0 && redCode.size() == 0 && blueCode.size() == 0) {
                    //没有选中球
                    toActivity();
                } else if (ballNumber.size() == 0 && redCode.size() == 0 && blueCode.size() == 0) {
                    //投注区没有选中任何一个
                    randomSelect();
                } else {
                    //投注区有，而且也有选中球
                    if (type.equals("ssq") && redCode.size() >= 6 && blueCode.size() >= 1) {
                        addSelector(true);
                    } else if (type.equals("dlt") && redCode.size() >= 5 && blueCode.size() >= 2) {
                        addSelector(true);
                    } else if (type.equals("qlc") && redCode.size() >= 7) {
                        addSelector(true);
                    }
                }
            }
        });
        mBottomBar.setCenterButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里我我们要实现的逻辑是添加到投注区里面；
                if (type.equals("ssq") && redCode.size() >= 6 && blueCode.size() >= 1) {
                    addSelector(false);
                } else if (type.equals("dlt") && redCode.size() >= 5 && blueCode.size() >= 2) {
                    addSelector(false);
                } else if (type.equals("qlc") && redCode.size() >= 7) {
                    addSelector(false);
                } else {
                    //这里我们是需要弹出一个对话框的显示没有选中相应的注数；
                }
            }
        });
        mBottomBar.setOnDragstateChangeListener(new Badge.OnDragStateChangedListener() {
            @Override
            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                if (dragState == Badge.OnDragStateChangedListener.STATE_SUCCEED) {
                    //这里表示拖动的状态；
                    //清空数据；
                    clearAllBetting();
                }
            }
        });

        initLotteryResultsView();
    }

    private void initLotteryResultsView() {
        //页面内开奖结果列表
        // LinearLayout ll_date = (LinearLayout) findViewById(R.id.ll_date);
        //  ll_date.setOnClickListener(this);
        iv_unfold = (ImageView) findViewById(R.id.iv_date_unfold);
        iv_unfold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVdlLayout.toggle();
            }
        });

        ll = (LinearLayout) findViewById(R.id.ll);
        lv_history = (ListView) findViewById(R.id.lv_history);
        lv_history.setDivider(null);
        // lv_history.setOnTouchListener(this);
        independentLotteryAdapter = new PLS_SD_QXCA_LotteryAdapter(this);
    }

    private void setMarginTop() {
        ViewTreeObserver vto2 = lv_history.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                lv_history.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                Log.e(TAG, "测量后的高度=" + lv_history.getHeight());
                topHeight = lv_history.getHeight();
                ll.setPadding(0, -topHeight, 0, 0);
            }
        });
    }

    int down; //手指按下的位置
    int move; //滑动的位置
    int difference;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                down = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                move = (int) event.getY();
                difference = move - down;
                if (move > down) {
                    int display = topHeight - difference;
                    //向下滑动时判断是关闭的
                    if (isClose) {
                        if (display >= 0 && display <= topHeight) {
                            ll.setPadding(0, -display, 0, 0);
                        }
                    }
                } else {
                    difference = move - down;
                    //向上滑动时判断是打开的
                    if (isClose == false) {
                        if (difference <= 0 && difference <= topHeight) {
                            ll.setPadding(0, difference, 0, 0);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (difference > (topHeight / 2)) {
                    ll.setPadding(0, 0, 0, 0);
                    isClose = false;
                    iv_unfold.setBackgroundResource(R.drawable.unfold_down);
                } else if (difference < (topHeight / 2) && difference != 0) {
                    ll.setPadding(0, -topHeight, 0, 0);
                    isClose = true;
                    iv_unfold.setBackgroundResource(R.drawable.unfold_up);
                }
                difference = 0;
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void initData() {

        mShakeUtils = new ShakeUtils(this);

        mShakeUtils.setOnShakeUtilsListener(new ShakeUtils.OnShakeUtilsListener() {
            @Override
            public void onShakedListener() {
                randomSelect();
            }

            @Override
            public void hasNotVibratorListener() {
            }
        });

        if (type.equals("ssq")) {
            setTitle("双色球");
            redCount = 33;
            blueCount = 16;
            redMultiple = 6;
            blueMultiple = 1;
            tv_hint.setText("至少选择6个红球1个蓝球");
        } else if (type.equals("dlt")) {
            setTitle("大乐透");
            redCount = 35;
            blueCount = 12;
            redMultiple = 5;
            blueMultiple = 2;
            tv_hint.setText("至少选择5个红球2个蓝球");
        } else if (type.equals("qlc")) {
            setTitle("七乐彩");
            redCount = 30;
            redMultiple = 7;
        }
        initBallList();     //这里初始化ball的一个列表；


        getMissData(type);  //请求数据；
        getIssueInfo(type);
        initPopupView();
        showDefaultBall();
        //接收来自其他地方的彩票号码直接显示
//        String redBall = getIntent().getStringExtra("redBall");
//        String blueBall = getIntent().getStringExtra("blueBall");
//        LinkedList<String> red = new LinkedList();
//        red.addAll(FastOk.getList(redBall, String.class));
//        LinkedList<String> blue = new LinkedList();
//        blue.addAll(FastOk.getList(blueBall, String.class));
//        randomSelect(red,blue);
    }

    void showDefaultBall() {
        //接收来自其他地方的彩票号码直接显示
        String redBall = getIntent().getStringExtra("redBall");
        String blueBall = getIntent().getStringExtra("blueBall");
        if (TextUtils.isEmpty(redBall) || TextUtils.isEmpty(blueBall)) return;
        clearBall();
        if (!TextUtils.isEmpty(redBall)) {
            List<String> red = FastOk.getList(redBall, String.class);
            for (int j = 0; j < red.size(); j++) {
                for (int i = 0; i < redBallsAdapter.getCount(); i++) {
                    BallItem ballItem = (BallItem) redBallsAdapter.getItem(i);
                    if (red.get(j).equals(ballItem.getBallNum())) {
                        redCode.add(red.get(j));
                        ballItem.setSelected(true);
                        break;
                    }
                }
            }
        }
        if (!TextUtils.isEmpty(blueBall)) {
            if (type.equals("ssq") || type.equals("dlt")) {
                List<String> blue = FastOk.getList(blueBall, String.class);
                for (int j = 0; j < blue.size(); j++) {
                    for (int i = 0; i < blueBallsAdapter.getCount(); i++) {
                        BallItem ballItem = (BallItem) blueBallsAdapter.getItem(i);
                        if (blue.get(j).equals(ballItem.getBallNum())) {
                            blueCode.add(blue.get(j));
                            ballItem.setSelected(true);
                            break;
                        }
                    }
                }
            }
        }

        redBallCount = redCode.size();
        blueBallCount = blueCode.size();
        setNumberMoney();
        redBallsAdapter.notifyDataSetChanged();
        blueBallsAdapter.notifyDataSetChanged();
        mBottomBar.setLeftText("机选");
        addSelector(true);
    }


    private void initPopupView() {
        View pv = View.inflate(this, R.layout.lottery_help_popupview, null);
        pop = new PopupWindow(pv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        TextView tv_trendChart = (TextView) pv.findViewById(R.id.tv_trendChart);
        tv_trendChart.setOnClickListener(this);
        TextView tv_kaijiang = (TextView) pv.findViewById(R.id.tv_kaijiang);
        tv_kaijiang.setOnClickListener(this);
        mTvMissData = (TextView) pv.findViewById(R.id.tv_missData);
        mTvMissData.setOnClickListener(this);

        (pv.findViewById(R.id.tv_play_desc)).setOnClickListener(this);

        if (PreferenceUtil.isShowMissing(this)) {
            showMissData();
        } else {
            hideMissData();
        }

        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mShakeUtils.unRegister();
    }

    private void randomSelect() {
        randomSelect(null, null);
    }

    /**
     * @category 机选
     */
    private void randomSelect(LinkedList<String> redList, LinkedList<String> blueList) {
        clearBall();
        LinkedList<String> red = redList == null ?
                MakeRandomUtil.getBall(redCount, redMultiple) : redList;
        for (int i = 0; i < redBallsAdapter.getCount(); i++) {
            BallItem ballItem = (BallItem) redBallsAdapter.getItem(i);
            for (int j = 0; j < red.size(); j++) {
                if (ballItem.getBallNum().equals(red.get(j))) {
                    redCode.add(red.get(j));
                    ballItem.setSelected(true);
                    break;
                }
            }
        }

        if (type.equals("ssq") || type.equals("dlt")) {
            LinkedList<String> blue = blueList == null ?
                    MakeRandomUtil.getBall(blueCount, blueMultiple) : blueList;
            for (int i = 0; i < blueBallsAdapter.getCount(); i++) {
                BallItem ballItem = (BallItem) blueBallsAdapter.getItem(i);
                for (int j = 0; j < blue.size(); j++) {
                    if (ballItem.getBallNum().equals(blue.get(j))) {
                        blueCode.add(blue.get(j));
                        ballItem.setSelected(true);
                        break;
                    }
                }
            }
        }

        redBallCount = redCode.size();
        blueBallCount = blueCode.size();
        setNumberMoney();
        redBallsAdapter.notifyDataSetChanged();
        blueBallsAdapter.notifyDataSetChanged();
        mBottomBar.setLeftText("机选");
    }

    //设置投注金额
    private void setNumberMoney() {
        int num = 0;
        if (type.equals("ssq")) {
            num = BaseUtils.math2(redBallCount, redMultiple) * BaseUtils.math2(blueBallCount, blueMultiple);
        } else if (type.equals("dlt")) {
            num = BaseUtils.math2(redBallCount, redMultiple) * BaseUtils.math2(blueBallCount, blueMultiple);
        } else if (type.equals("qlc")) {
            num = BaseUtils.math2(redBallCount, redMultiple);
        } else if (type.equals("sdsyxw")) {
        }
        int moeny = num * 2;
        //tv_number_money.setText(Html.fromHtml("共" + num + "注，<font color=red>" + moeny + "</font>元"));
        if (num > 0) {
            tv_number_money.setVisibility(View.VISIBLE);
            tv_number_money.setText(num + "注 , " + moeny + "元");
        } else {
            tv_number_money.setVisibility(View.INVISIBLE);
        }
        if (num == 0) {
            mBottomBar.setLeftText("机选");
        } else {
            mBottomBar.setLeftText("清空");
        }
    }

    //清空选中
    private void clearBall() {
        for (int i = 0; i < redBallsAdapter.getCount(); i++) {
            BallItem ballItem = (BallItem) redBallsAdapter.getItem(i);
            ballItem.setSelected(false);
        }
        for (int i = 0; i < blueBallsAdapter.getCount(); i++) {
            BallItem ballItem = (BallItem) blueBallsAdapter.getItem(i);
            ballItem.setSelected(false);
        }
        redCode.clear();
        blueCode.clear();
        redBallCount = 0;
        blueBallCount = 0;
        redBallsAdapter.notifyDataSetChanged();
        blueBallsAdapter.notifyDataSetChanged();
        // tv_number_money.setText(Html.fromHtml("共0注，<font color=red>0</font>元"));
        tv_number_money.setText("0注 , 0元");

        //ll_bottom.setVisibility(View.INVISIBLE);
        tv_number_money.setVisibility(View.INVISIBLE);
        mBottomBar.setLeftText("机选");
    }

    /**
     * //     * @param bean
     *
     * @category 初始化球列表
     */
    private void initBallList() {
        int redSubscript = 0;
        int blueSubscript = 0;
        //红球数
        int redNums = 1;
        //蓝球数
        int blueNums = 1;
        //球item
        BallItem ballItem = null;


        //添加32个红球数据，前9个红球前缀加0
        while (true) {
            if (redNums > redCount) {
                break;
            }
            if (redNums < 10) {
                ballItem = new BallItem("0" + redNums, false, true);
            } else {
                ballItem = new BallItem("" + redNums, false, true);
            }
            redBallsAdapter.addItem(ballItem);
            redNums++;
        }

        if (type.equals("ssq") || type.equals("dlt")) {
            // String[] blueCode = omission.getBlue().split(",");
            //添加蓝球数据，前9个蓝球前缀加0
            while (true) {
                if (blueNums > blueCount) {
                    break;
                }
                if (blueNums < 10) {
                    ballItem = new BallItem("0" + blueNums, false, false);
                } else {
                    ballItem = new BallItem("" + blueNums, false, false);
                }
                blueBallsAdapter.addItem(ballItem);
                blueNums++;
            }
        }

    }

    @OnClick(R.id.tv_right_option)
    void showHelpMenu() {
        int height = rlBar.getHeight();
        int statusHeight = BaseUtils.getStatusHeight(this);
        int width = BaseUtils.getDisplaySize(this, "width");
        pop.showAtLocation(rlBar, 0, width, statusHeight + height);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //摇一摇选号
            case R.id.iv_shake:
                randomSelect();
                break;
            //清空
            case R.id.bt_bottom_left:
                clearBall();
                break;
            case R.id.tv_kaijiang:
                Intent intent = new Intent(this, LotteryHistoryActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.tv_trendChart:
                //这里我们要做一个操作就是跳转；
                intent = new Intent(this, LottoTrendActivity.class);

                if (type.equals("ssq")) {
                    intent.putExtra("lotteryId", LotteryType.SSQ);
                    intent.putExtra("title", "双色球");
                } else if (type.equals("dlt")) {
                    intent.putExtra("lotteryId", LotteryType.DLT);
                    intent.putExtra("title", "大乐透");
                } else if (type.equals("qlc")) {
                    intent.putExtra("lotteryId", LotteryType.QLC);
                    intent.putExtra("title", "七乐彩");
                }
                startActivity(intent);

                break;
            case R.id.ll_date:
                if (isClose) {
                    //展开
                    iv_unfold.setBackgroundResource(R.drawable.unfold_up);
                    ll.setPadding(0, -topHeight, 0, 0);
                    isClose = false;
                } else {
                    //关闭
                    iv_unfold.setBackgroundResource(R.drawable.unfold_down);
                    ll.setPadding(0, 0, 0, 0);
                    isClose = true;
                }
                break;
            case R.id.tv_missData:
                //是否显示遗漏：
                boolean showMissing = PreferenceUtil.isShowMissing(this);
                showMissing = !showMissing;
                if (showMissing) {
                    showMissData();
                } else {
                    hideMissData();
                }
                pop.dismiss();
                break;
            case R.id.tv_play_desc:

                Intent helpIntent = new Intent(this, WebHelperActivity.class);
                helpIntent.putExtra("title", "玩法介绍");
                helpIntent.putExtra("code", type);
                helpIntent.putExtra("isLocal", true);
                startActivity(helpIntent);
                break;
        }
    }

    public void showMissData() {
        //这里我们要拿到红色的和蓝色的adapter;
        redBallsAdapter.showMissData();
        if (!type.equals("qcl")) {
            blueBallsAdapter.showMissData();
        }
        //显示遗漏
        mTvMissData.setText("隐藏遗漏");
        PreferenceUtil.setIsShowMissing(this, true);
        //这里VDLayou里面没有对Outter的高度进行一个测量保存，
        // 所以这里我们是需要重新对其进行一个测量和保存的；
        mVdlLayout.measuerOutterLayout();
    }

    public void hideMissData() {
        redBallsAdapter.hideMissData();
        if (!type.equals("qcl")) {
            blueBallsAdapter.hideMissData();
        }
        //隐藏遗漏
        mTvMissData.setText("显示遗漏");
        PreferenceUtil.setIsShowMissing(this, false);
        //这里VDLayou里面没有对Outter的高度进行一个测量保存，
        // 所以这里我们是需要重新对其进行一个测量和保存的；
        mVdlLayout.measuerOutterLayout();
    }

    boolean isClose = true;


    //构造球数据
    @Override
    public View onItemChanged(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        BallItem ballItem = null;
        int mViewGroup = 0;
        BallsAdapter ballsAdapter = null;

        if (parent.getId() == R.id.gridview_ssq_red_ball) {

            ballsAdapter = redBallsAdapter;
        } else if (parent.getId() == R.id.gridview_ssq_blue_ball) {

            ballsAdapter = blueBallsAdapter;
        }

        ballItem = ((BallItem) ballsAdapter.getItem(position));
        mViewGroup = R.layout.ballgridview_ball_item;

        if (null == convertView) {
            holder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(this);
            convertView = inflater.inflate(mViewGroup, parent, false);
            //convertView = inflater.inflate(mViewGroup, null, false);
            holder.ball_num = (TextView) convertView.findViewById(R.id.txt_ball_num);
            holder.tv_missData = (TextView) convertView.findViewById(R.id.tv_missData);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //获取球的一些信息；
        String num = ballItem.getBallNum();
        boolean selected = ballItem.isSelected();
        boolean color = ballItem.isColor();

        holder.ball_num.setText(num);
        if (ballsAdapter.getMissDataInfo().length > 0) {
            holder.tv_missData.setText(ballsAdapter.getMissDataInfo()[position]);
        } else {
            holder.tv_missData.setText("-");
        }

        if (ballsAdapter.isShowMissData()) {
            holder.tv_missData.setVisibility(View.VISIBLE);
        } else {
            holder.tv_missData.setVisibility(View.GONE);
        }

        Log.e(TAG, "position=" + position);

        if (selected) {
            if (color) {
                holder.ball_num.setBackgroundResource(R.drawable.red_ball);
                holder.ball_num.setTextColor(Color.WHITE);
            } else {
                holder.ball_num.setBackgroundResource(R.drawable.blue_ball);
                holder.ball_num.setTextColor(Color.WHITE);
            }
            startBallAnimation(holder.ball_num);
        } else {
            holder.ball_num.setBackgroundResource(R.drawable.ball_normal);
            if (color) {
                holder.ball_num.setTextColor(getResources().getColor(R.color.baseRed));
                //这里的话，我们还需要设置textView的背景；
                holder.ball_num.setBackgroundResource(R.drawable.shape_ball_red_bg);
            } else {
                holder.ball_num.setTextColor(getResources().getColor(R.color.baseBlue));
                //这里的话，我们还需要设置textView的背景；
                holder.ball_num.setBackgroundResource(R.drawable.shape_ball_blue_bg);
            }
        }
        return convertView;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        View ball = view.findViewById(R.id.txt_ball_num);

        if (parent.getId() == R.id.gridview_ssq_red_ball) {
            if (type.equals("sdsyxw")) {
                redMultiple = position;
            }
            BallItem ballItem = (BallItem) redBallsAdapter.getItem(position);


            if (!ballItem.isSelected()) {
                ballItem.setSelected(true);
                redBallCount++;
                redCode.add(ballItem.getBallNum());
                //这里的话，我们是需要给这个球增加一个动画的；
                startBallAnimation(ball);
            } else {
                ballItem.setSelected(false);
                redBallCount--;
                redCode.remove(ballItem.getBallNum());
            }
            setNumberMoney();
            redBallsAdapter.notifyDataSetChanged();

        } else if (parent.getId() == R.id.gridview_ssq_blue_ball) {

            BallItem ballItem = (BallItem) blueBallsAdapter.getItem(position);
            if (!ballItem.isSelected()) {

                ballItem.setSelected(true);
                blueBallCount++;
                blueCode.add(ballItem.getBallNum());
                //这里的话，我们是需要给这个球增加一个动画的；
                startBallAnimation(ball);
            } else {
                ballItem.setSelected(false);
                blueBallCount--;
                blueCode.remove(ballItem.getBallNum());
            }
            setNumberMoney();
            blueBallsAdapter.notifyDataSetChanged();
        }

        //这里的话，我们通过判断来动态显示ll_bottom;
        if (type.equals("ssq") && redCode.size() >= 6 && blueCode.size() >= 1) {
            tv_number_money.setVisibility(View.VISIBLE);
        } else if (type.equals("dlt") && redCode.size() >= 5 && blueCode.size() >= 2) {
            tv_number_money.setVisibility(View.VISIBLE);
        } else if (type.equals("qlc") && redCode.size() >= 7) {
            tv_number_money.setVisibility(View.VISIBLE);
        } else {
            tv_number_money.setVisibility(View.INVISIBLE);
        }

        //这里我们是需要做一个判断；
        if (redCode.size() > 0 || blueCode.size() > 0) {
            mBottomBar.setLeftText("清空");
        } else {
            mBottomBar.setLeftText("机选");
        }
    }

    protected class ViewHolder {
        public TextView ball_num;
        public TextView tv_missData;
    }


    private void getMissData(String type) {

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type",type);
        HttpManager.postAsyn(Constant_Url.GET_MISS_DATA, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response) {
                try {
                    MissDataBean bean = FastOk.get(response, MissDataBean.class);
                    if (bean != null) {
                        setMissData(bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        },paramsMap);

        //showDialog();
 /*       OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.GET_MISS_DATA);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {
                    MissDataBean bean = FastOk.get(json, MissDataBean.class);

                    setMissData(bean);

                }

                @Override
                public void onError() {
                    ToastUtil.showToast(BetSSQ_DLT_QLCActivity.this, R.string.connect_failure);
                    //dissDialog();
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
            //dissDialog();
        }*/

    }

    public int measureListViewWrongHeight(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        topHeight = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        params.height = topHeight;
        listView.setLayoutParams(params);
        return totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    }


    //设置遗漏和历史记录；
    private void setMissData(MissDataBean bean) {
        if (bean==null) {
            return;
        }
        try {
            if (bean.getCodes() != null) {
                independentLotteryAdapter.setData(bean.getCodes());
                lv_history.setAdapter(independentLotteryAdapter);
            }
            int height = measureListViewWrongHeight(lv_history);

            lv_history.getLayoutParams().height = height;
            lv_history.requestLayout();
            mVdlLayout.measureInnerLayout();

//        MissDataBean.Omission omission = bean.getOmission();
//        if (omission == null) return;
//        String[] redCode = omission.getRed().split(",");

            //这里的话，我们要做的一个操作就是，我们可以将遗漏通过数组的形式传递过去；
            if (bean.getOmission() != null) {
                redBallsAdapter.addMissDataInfo(bean.getOmission().getRed());
                if (!type.equals("qlc")) {
                    //大乐透没有蓝球
                    blueBallsAdapter.addMissDataInfo(bean.getOmission().getBlue());
                }
            }
        } catch (Exception e) {

        }
        redBallsAdapter.notifyDataSetChanged();
        blueBallsAdapter.notifyDataSetChanged();
    }

    private void getIssueInfo(String type) {

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("type",type);

        HttpManager.postAsyn(Constant_Url.ISSUE_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！");
            }

            @Override
            public void onResponse(String response) {
                try {
                    IssueInfoBean bean = FastOk.get(response, IssueInfoBean.class);
                    if (bean != null) {
                        setViewInfo(bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },paramsMap);

/*        OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.ISSUE_INFO);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {
                    IssueInfoBean bean = FastOk.get(json, IssueInfoBean.class);
                    setViewInfo(bean);
                }

                @Override
                public void onError() {
                    ToastUtil.showToast(BetSSQ_DLT_QLCActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    private void setViewInfo(IssueInfoBean bean) {
        if (bean == null) return;
        tv_term.setText(Html.fromHtml("期号:<font color=red>" + bean.getTermNo() + "</font>"));
       // tv_date.setText("截止时间:" + bean.getStopSaleTime());
        tv_date.setText(Html.fromHtml("截止时间:<font color=red>" + bean.getStopSaleTime() + "</font>"));

    }

//    boolean isTo;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        boolean isTo = false;
        boolean restrict = false;

        if (event.getAction() == MotionEvent.ACTION_UP) {
            iv_add_selector.setBackgroundResource(R.drawable.add_off);

            if (v.getId() == R.id.rl_add || v.getId() == R.id.bt_bottom_right) {
                if (v.getId() == R.id.bt_bottom_right) {
                    isTo = true;
                    if (ballNumber.size() > 0 && redCode.size() == 0 && blueCode.size() == 0) {
                        toActivity();
                    } else if (ballNumber.size() == 0 && redCode.size() == 0 && blueCode.size() == 0) {
                        randomSelect();
                    } else {
                        restrict = true;
                    }
                } else {
                    restrict = true;
                }
            }
            if (restrict) {
                if (type.equals("ssq") && redCode.size() >= 6 && blueCode.size() >= 1) {
                    addSelector(isTo);
                } else if (type.equals("dlt") && redCode.size() >= 5 && blueCode.size() >= 2) {
                    addSelector(isTo);
                } else if (type.equals("qlc") && redCode.size() >= 7) {
                    addSelector(isTo);
                }
            }
        }

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (v.getId() == R.id.rl_add) {
                iv_add_selector.setBackgroundResource(R.drawable.add_on);
            }
        }
        return true;
    }


    private void formatBallNumber() {

        //不断生成销毁，数据由codeOnes决定
        StringBuffer redBuffer = null;
        StringBuffer blueBufferTwo = null;
        int num = 0;
        int money = 0;

        if (type.equals("dlt") || type.equals("ssq")) {
            redBuffer = new StringBuffer();
            for (int j = 0; j < redCode.size(); j++) {
                if (j == redCode.size() - 1) {
                    redBuffer.append(redCode.get(j));
                } else {
                    redBuffer.append(redCode.get(j) + ",");
                }
            }

            blueBufferTwo = new StringBuffer();
            for (int j = 0; j < blueCode.size(); j++) {
                if (j == blueCode.size() - 1) {
                    blueBufferTwo.append(blueCode.get(j));
                } else {
                    blueBufferTwo.append(blueCode.get(j) + ",");
                }
            }
            ballNumber.add(redBuffer.toString() + "|" + blueBufferTwo.toString());
            num = BaseUtils.math2(redBallCount, redMultiple) * BaseUtils.math2(blueBallCount, blueMultiple);
            if (type.equals("dlt")) {
                if (redCode.size() > 5 || blueCode.size() > 2) {
                    mode.add("大乐透 复式");
                } else {
                    mode.add("大乐透 单式");
                }
            } else if (type.equals("ssq")) {
                if (redCode.size() > 6 || blueCode.size() > 1) {
                    mode.add("双色球 复式");
                } else {
                    mode.add("双色球 单式");
                }
            }
        } else {
            redBuffer = new StringBuffer();
            for (int j = 0; j < redCode.size(); j++) {
                if (j == redCode.size() - 1) {
                    redBuffer.append(redCode.get(j));
                } else {
                    redBuffer.append(redCode.get(j) + ",");
                }
            }
            ballNumber.add(redBuffer.toString());
            num = BaseUtils.math2(redBallCount, redMultiple);

            if (redCode.size() > 7) {
                mode.add("七星彩 复式");
            } else {
                mode.add("七星彩 单式");
            }

        }
        money = num * 2;
        numMoney.add(num + "注" + " " + money + "元");
        totalMoney += money;
        totalNum += num;

        mBottomBar.setBettingNumber(totalNum);
    }


    private void toActivity() {
        Intent intent = new Intent(this, BetConfirmActivity.class);
        intent.putExtra("type", type); //彩种
        intent.putExtra("totalMoney", totalMoney); //总金额
        intent.putExtra("totalNum", totalNum); //总注数
        intent.putStringArrayListExtra("ballNumber", ballNumber); //球
        intent.putStringArrayListExtra("mode", mode); //玩法及模式
        intent.putStringArrayListExtra("numMoney", numMoney); //注数及金额
        startActivityForResult(intent, 0);
    }

    private void addSelector(boolean isTo) {
        formatBallNumber();
        tv_count.setVisibility(View.VISIBLE);
        tv_count.setText(String.valueOf(ballNumber.size()));

        if (isTo) {
            toActivity();
        }
        clearBall();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) return;
        switch (resultCode) {
            case 0:
                Log.i(TAG, "继续选号");
                ballNumber = data.getStringArrayListExtra("ballNumber");
                mode = data.getStringArrayListExtra("mode");
                numMoney = data.getStringArrayListExtra("numMoney");
                totalMoney = data.getIntExtra("totalMoney", totalMoney);
                totalNum = data.getIntExtra("totalNum", totalNum);
                tv_count.setVisibility(View.VISIBLE);
                tv_count.setText(String.valueOf(ballNumber.size()));

                mBottomBar.setBettingNumber(totalNum);
                break;
            case 1:
                Log.i(TAG, "清除选号");
                clearAllBetting();
                break;
            case -1:
                this.finish();
                break;
        }
    }

    private void clearAllBetting() {
        ballNumber.clear();
        mode.clear();
        numMoney.clear();
        totalMoney = 0;
        totalNum = 0;
        tv_count.setVisibility(View.GONE);
        mBottomBar.setBettingNumber(totalNum);
    }

    /**
     * 这里是从未选中到选中的一个缩放动画；
     */
    public void startBallAnimation(View view) {
        //一个缩放动画；
        AnimatorSet animatorSet = new AnimatorSet();

        ObjectAnimator animator1 = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.8f, 1f);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.8f, 1f);

        animatorSet.playTogether(animator1, animator2);
        animatorSet.setDuration(200);
        animatorSet.start();
    }

    @Override
    protected void sendRandom(Intent intent) {
        super.sendRandom(intent);
//机选
        int num = intent.getIntExtra("num", 0);
        if (num > 0) {
            clearAllBetting();
            //开始机选
            for (int i = 0; i < num; i++) {
                randomSelect();
                addSelector(false);
            }
            intent.setAction(Constant_Result.EXECRANDOMLOTTERYNUM);
            intent.putExtra("type", type); //彩种
            intent.putExtra("totalMoney", totalMoney); //总金额
            intent.putExtra("totalNum", totalNum); //总注数
            intent.putStringArrayListExtra("ballNumber", ballNumber); //球
            intent.putStringArrayListExtra("mode", mode); //玩法及模式
            intent.putStringArrayListExtra("numMoney", numMoney); //注数及金额
            sendBroadcast(intent);
        }
    }
}
